package com.fdd.furns.web;

import com.fdd.furns.pojo.Cart;
import com.fdd.furns.pojo.Order;
import com.fdd.furns.service.OrderService;
import com.fdd.furns.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import com.fdd.furns.pojo.Member;
import com.fdd.furns.utils.JDBCUtilsByDruid;

@WebServlet(urlPatterns = "/orderServlet")
public class OrderServlet extends BasicServlet {
    OrderService orderService = new OrderServiceImpl();

    protected void saveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //没有购买任何家居
        if (cart == null || cart.getItems().isEmpty()) {
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }
        Member member = (Member) req.getSession().getAttribute("member");

        if (member == null) {
            //没有登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/views/member/login.jsp");
            return;
        }

        //调用orderService.saveOrder() 完成保存订单
//        String orderId = null;
//        try {
//            orderId = orderService.saveOrder(cart, member.getId());
//            JDBCUtilsByDruid.commit();
//        } catch (Exception e) {
//            JDBCUtilsByDruid.rollback();
//            throw new RuntimeException(e);
//        }
//        req.getSession().setAttribute("orderId", orderId);
        String orderId = orderService.saveOrder(cart, member.getId());
        //将订单号保存到session中，后面要展示订单号
        req.getSession().setAttribute("orderId", orderId);

        //重定向到checkout.jsp
        resp.sendRedirect(req.getContextPath() + "/views/order/checkout.jsp");
    }

    protected void ordersList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入了ordersList方法");
        Member member = (Member) req.getSession().getAttribute("member");
        if (member == null) {
            //没有登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/views/member/login.jsp");
        } else {
            List<Order> orderList = orderService.getOrderByMemberId(member.getId());
            // 添加调试信息
            for (Order order : orderList) {
                System.out.println("订单日期: " + order.getCreateTime());
            }
            req.setAttribute("orderList", orderList);
            req.getRequestDispatcher("/views/order/order.jsp").forward(req, resp);
        }
    }


}
